import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../controllers/video_list_controller.dart';
import '../../../routes/app_pages.dart';

class VideoListView extends GetView<VideoListController> {
  const VideoListView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFEDF3FA),
      appBar: _buildAppBar(),
      body: Obx(() {
        return ListView(
          children: [
            // 自定义时间选择区域（仅在云存模式下显示）
            if (controller.storageType.value == 'cloud')
              _buildCustomTimeSection(),

            Container(
              padding: EdgeInsets.symmetric(horizontal: 32.w, vertical: 20.h),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  SizedBox(height: 20.h),
                  Text(
                    '固定录像文件',
                    style: TextStyle(
                      fontSize: 28.sp,
                      fontWeight: FontWeight.w600,
                      color: const Color(0xFF333333),
                    ),
                  ),
                  SizedBox(height: 16.h),
                  Obx(
                    () => GestureDetector(
                      onTap: _showDatePicker,
                      child: Container(
                        padding: EdgeInsets.symmetric(
                          horizontal: 16.w,
                          vertical: 12.h,
                        ),
                        decoration: BoxDecoration(
                          color: const Color(0xFFF8F9FA),
                          borderRadius: BorderRadius.circular(8.r),
                          border: Border.all(color: const Color(0xFFE5E7EB)),
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(
                              controller.selectedDate.value,
                              style: TextStyle(
                                fontSize: 24.sp,
                                color: const Color(0xFF333333),
                              ),
                            ),
                            Icon(
                              Icons.keyboard_arrow_down,
                              size: 24.sp,
                              color: const Color(0xFF999999),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),

            _buildVideoListContent(),
          ],
        );
      }),
      // 右下角悬浮按钮
      floatingActionButton: _buildFloatingButtons(),
    );
  }

  /// 构建AppBar
  PreferredSizeWidget _buildAppBar() {
    return AppBar(
      surfaceTintColor: Colors.white,
      backgroundColor: const Color(0xFFFFFFFF),
      elevation: 0,
      leading: IconButton(
        onPressed: () => Get.back(),
        icon: Icon(
          Icons.arrow_back_ios,
          size: 40.w,
          color: const Color(0xFF333333),
        ),
      ),
      title: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          _buildTabButton('云存', 'cloud'),
          SizedBox(width: 40.w),
          _buildTabButton('本地存储', 'local'),
        ],
      ),
      centerTitle: true,
    );
  }

  /// 构建Tab按钮
  Widget _buildTabButton(String title, String type) {
    return Obx(() {
      final isSelected = controller.storageType.value == type;
      return GestureDetector(
        onTap: () => controller.switchStorageType(type),
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 24.w, vertical: 12.h),
          decoration: BoxDecoration(
            border: Border(
              bottom: BorderSide(
                color:
                    isSelected ? const Color(0xFF047FF7) : Colors.transparent,
                width: 3.w,
              ),
            ),
          ),
          child: Text(
            title,
            style: TextStyle(
              fontSize: 32.sp,
              fontWeight: isSelected ? FontWeight.w600 : FontWeight.w400,
              color:
                  isSelected
                      ? const Color(0xFF047FF7)
                      : const Color(0xFF999999),
            ),
          ),
        ),
      );
    });
  }

  /// 构建自定义时间选择区域
  Widget _buildCustomTimeSection() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 32.w, vertical: 20.h),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '自定义时间下载',
            style: TextStyle(
              fontSize: 28.sp,
              fontWeight: FontWeight.w600,
              color: const Color(0xFF333333),
            ),
          ),
          SizedBox(height: 20.h),
          // 时间选择按钮
          Row(
            children: [
              Expanded(
                child: Obx(
                  () => GestureDetector(
                    onTap: () {
                      // 点击时先清空开始时间
                      controller.clearStartTime();
                      _showTimePicker(true);
                    },
                    child: Container(
                      padding: EdgeInsets.symmetric(
                        horizontal: 16.w,
                        vertical: 12.h,
                      ),
                      decoration: BoxDecoration(
                        color:
                            controller.startTime.value.isNotEmpty
                                ? const Color(0xFFF0F8FF)
                                : const Color(0xFFF8F9FA),
                        borderRadius: BorderRadius.circular(8.r),
                        border: Border.all(
                          color:
                              controller.startTime.value.isNotEmpty
                                  ? const Color(0xFF047FF7)
                                  : const Color(0xFFE5E7EB),
                        ),
                      ),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            controller.startTime.value.isNotEmpty
                                ? controller.startTime.value
                                : '开始时间',
                            style: TextStyle(
                              fontSize: 24.sp,
                              color:
                                  controller.startTime.value.isNotEmpty
                                      ? const Color(0xFF047FF7)
                                      : const Color(0xFF666666),
                            ),
                          ),
                          Icon(
                            Icons.access_time,
                            size: 20.sp,
                            color: const Color(0xFF999999),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
              ),
              SizedBox(width: 16.w),
              Expanded(
                child: Obx(
                  () => GestureDetector(
                    onTap: () {
                      // 点击时先清空结束时间
                      controller.clearEndTime();
                      _showTimePicker(false);
                    },
                    child: Container(
                      padding: EdgeInsets.symmetric(
                        horizontal: 16.w,
                        vertical: 12.h,
                      ),
                      decoration: BoxDecoration(
                        color:
                            controller.endTime.value.isNotEmpty
                                ? const Color(0xFFF0F8FF)
                                : const Color(0xFFF8F9FA),
                        borderRadius: BorderRadius.circular(8.r),
                        border: Border.all(
                          color:
                              controller.endTime.value.isNotEmpty
                                  ? const Color(0xFF047FF7)
                                  : const Color(0xFFE5E7EB),
                        ),
                      ),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            controller.endTime.value.isNotEmpty
                                ? controller.endTime.value
                                : '结束时间',
                            style: TextStyle(
                              fontSize: 24.sp,
                              color:
                                  controller.endTime.value.isNotEmpty
                                      ? const Color(0xFF047FF7)
                                      : const Color(0xFF666666),
                            ),
                          ),
                          Icon(
                            Icons.access_time,
                            size: 20.sp,
                            color: const Color(0xFF999999),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  /// 构建视频列表内容
  Widget _buildVideoListContent() {
    return Obx(() {
      if (controller.isLoading.value) {
        return Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              CircularProgressIndicator(color: const Color(0xFF047FF7)),
              SizedBox(height: 20.h),
              Text(
                '正在加载录像数据...',
                style: TextStyle(
                  fontSize: 28.sp,
                  color: const Color(0xFF999999),
                ),
              ),
            ],
          ),
        );
      }

      final videos = controller.videoList;
      if (videos.isEmpty) {
        return Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Image.asset(
                'assets/images/null.png',
                width: 200.w,
                height: 200.w,
              ),
              SizedBox(height: 20.h),
              Text(
                '暂无录像数据',
                style: TextStyle(
                  fontSize: 28.sp,
                  color: const Color(0xFF999999),
                ),
              ),
            ],
          ),
        );
      }

      // 按小时分组显示录像
      final groupedSegments = _groupSegmentsByHour(videos);

      return ListView.builder(
        shrinkWrap: true,
        physics: NeverScrollableScrollPhysics(),
        padding: EdgeInsets.all(16.w),
        itemCount: groupedSegments.keys.length,
        itemBuilder: (context, index) {
          final hour = groupedSegments.keys.elementAt(index);
          final hourSegments = groupedSegments[hour]!;
          return _buildDownloadHourGroup(hour, hourSegments);
        },
      );
    });
  }

  /// 按小时分组录像片段
  Map<int, List<Map<String, dynamic>>> _groupSegmentsByHour(
    List<Map<String, dynamic>> segments,
  ) {
    final Map<int, List<Map<String, dynamic>>> grouped = {};

    for (final segment in segments) {
      final hour = segment['hour'] as int? ?? 0;
      if (grouped[hour] == null) {
        grouped[hour] = [];
      }
      grouped[hour]!.add(segment);
    }

    return grouped;
  }

  /// 构建下载模式小时分组
  Widget _buildDownloadHourGroup(
    int hour,
    List<Map<String, dynamic>> hourSegments,
  ) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 小时标题
        Padding(
          padding: EdgeInsets.symmetric(vertical: 16.h, horizontal: 16.w),
          child: Text(
            '${hour.toString().padLeft(2, '0')}:00',
            style: TextStyle(
              fontSize: 28.sp,
              fontWeight: FontWeight.w600,
              color: Color(0xFF333333),
            ),
          ),
        ),

        // 该小时的录像片段网格（每行3个）
        GridView.builder(
          shrinkWrap: true,
          physics: const NeverScrollableScrollPhysics(),
          padding: EdgeInsets.symmetric(horizontal: 16.w),
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 3,
            crossAxisSpacing: 12.w,
            mainAxisSpacing: 12.h,
            childAspectRatio: 0.8, // 稍微高一点的比例
          ),
          itemCount: hourSegments.length,
          itemBuilder: (context, index) {
            final segment = hourSegments[index];
            return _buildDownloadRecordItem(segment);
          },
        ),
      ],
    );
  }

  /// 构建下载模式录像项（封面+下载图标）
  Widget _buildDownloadRecordItem(Map<String, dynamic> segment) {
    final time = segment['time'] as String? ?? '';
    final duration = segment['duration'] as String? ?? '';
    final type = segment['type'] as String? ?? 'motion';
    final picUrl = segment['picUrl'] as String?;

    return GestureDetector(
      onTap: () {
        // 处理录像下载
        controller.handleRecordDownload(segment);
      },
      child: Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(12.r),
          border: Border.all(color: Color(0xFFE5E7EB), width: 1.w),
        ),
        child: ClipRRect(
          borderRadius: BorderRadius.circular(12.r),
          child: Stack(
            children: [
              // 录像封面背景
              picUrl != null && picUrl.isNotEmpty
                  ? Image.network(
                    picUrl,
                    width: double.infinity,
                    height: double.infinity,
                    fit: BoxFit.cover,
                    errorBuilder: (context, error, stackTrace) {
                      return _buildDefaultBackground(type);
                    },
                  )
                  : _buildDefaultBackground(type),

              // 时间标签
              Positioned(
                top: 8.h,
                left: 8.w,
                child: Container(
                  padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h),
                  decoration: BoxDecoration(
                    color: Colors.black54,
                    borderRadius: BorderRadius.circular(4.r),
                  ),
                  child: Text(
                    time,
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 18.sp,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
              ),

              // 时长标签
              Positioned(
                bottom: 8.h,
                right: 8.w,
                child: Container(
                  padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 4.h),
                  decoration: BoxDecoration(
                    color: Colors.black54,
                    borderRadius: BorderRadius.circular(4.r),
                  ),
                  child: Text(
                    duration,
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 16.sp,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ),
              ),

              // 录像类型标签（左下角）
              if (type != 'unknown')
                Positioned(
                  bottom: 8.h,
                  left: 8.w,
                  child: Container(
                    padding: EdgeInsets.symmetric(
                      horizontal: 6.w,
                      vertical: 2.h,
                    ),
                    decoration: BoxDecoration(
                      color:
                          type == 'alarm'
                              ? Color(0xFFFF4444)
                              : Color(0xFF047FF7),
                      borderRadius: BorderRadius.circular(3.r),
                    ),
                    child: Text(
                      type == 'alarm' ? '告警' : '定时',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 12.sp,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ),
                ),

              // 下载图标覆盖层（居中）
              Positioned.fill(
                child: Container(
                  decoration: BoxDecoration(
                    color: Colors.black.withValues(alpha: 0.3),
                  ),
                  child: Center(
                    child: Container(
                      width: 48.w,
                      height: 48.w,
                      decoration: BoxDecoration(
                        color: Color(0xFF047FF7),
                        shape: BoxShape.circle,
                      ),
                      child: Icon(
                        Icons.download,
                        color: Colors.white,
                        size: 24.w,
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建悬浮按钮
  Widget _buildFloatingButtons() {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Container(
          width: 110.w,
          height: 110.w,
          decoration: BoxDecoration(
            color: const Color(0xFF047FF7),
            shape: BoxShape.circle,
            boxShadow: [
              BoxShadow(
                color: const Color(0xFF047FF7).withValues(alpha: 0.3),
                blurRadius: 8,
                offset: const Offset(0, 4),
              ),
            ],
          ),
          child: Material(
            color: Colors.transparent,
            child: InkWell(
              borderRadius: BorderRadius.circular(40.w),
              onTap: () => Get.back(),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(Icons.play_arrow, color: Colors.white, size: 22),
                  SizedBox(height: 2.h),
                  Text(
                    '回放',
                    style: TextStyle(
                      fontSize: 11,
                      color: Colors.white,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
        SizedBox(height: 32.h),

        // 我的下载按钮
        Container(
          width: 110.w,
          height: 110.w,
          decoration: BoxDecoration(
            color: const Color(0xFF047FF7),
            shape: BoxShape.circle,
            boxShadow: [
              BoxShadow(
                color: const Color(0xFF047FF7).withValues(alpha: 0.3),
                blurRadius: 8,
                offset: const Offset(0, 4),
              ),
            ],
          ),
          child: Material(
            color: Colors.transparent,
            child: InkWell(
              borderRadius: BorderRadius.circular(40.w),
              onTap: () {
                Get.toNamed(Routes.DOWNLOAD);
              },
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(Icons.download, color: Colors.white, size: 23),
                  SizedBox(height: 2.h),
                  Text(
                    '我的下载',
                    style: TextStyle(
                      fontSize: 10,
                      color: Colors.white,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),

        SizedBox(height: 376.h),
      ],
    );
  }

  /// 显示自定义时间选择器
  void _showTimePicker(bool isStartTime) {
    // 获取初始时间
    DateTime initialDateTime;
    DateTime? minDate;
    DateTime? maxDate;

    if (isStartTime) {
      // 选择开始时间
      if (controller.startTime.value.isNotEmpty) {
        try {
          initialDateTime = DateTime.parse(
            controller.startTime.value.replaceAll(' ', 'T'),
          );
        } catch (e) {
          initialDateTime = DateTime.now();
        }
      } else {
        // 开始时间的秒数从00开始
        final now = DateTime.now();
        initialDateTime = DateTime(
          now.year,
          now.month,
          now.day,
          now.hour,
          now.minute,
          0, // 秒数从00开始
        );
      }

      // 如果已有结束时间，开始时间不能晚于结束时间
      if (controller.endTime.value.isNotEmpty) {
        try {
          final endDateTime = DateTime.parse(
            controller.endTime.value.replaceAll(' ', 'T'),
          );
          maxDate = endDateTime;
        } catch (e) {
          maxDate = DateTime.now();
        }
      } else {
        maxDate = DateTime.now();
      }
      minDate = DateTime(2020, 1, 1);
    } else {
      // 选择结束时间
      if (controller.endTime.value.isNotEmpty) {
        try {
          initialDateTime = DateTime.parse(
            controller.endTime.value.replaceAll(' ', 'T'),
          );
        } catch (e) {
          initialDateTime = DateTime.now();
        }
      } else {
        initialDateTime = DateTime.now();
      }

      // 结束时间必须晚于开始时间，且不能超过开始时间+1小时
      if (controller.startTime.value.isNotEmpty) {
        try {
          final startDateTime = DateTime.parse(
            controller.startTime.value.replaceAll(' ', 'T'),
          );
          // 最小时间：如果同一分钟，则开始时间+1秒；否则就是开始时间
          // 但为了允许选择同一分钟，我们设置最小时间为开始时间
          // 实际验证在onDateTimeChanged中进行
          minDate = startDateTime;
          maxDate = startDateTime.add(const Duration(hours: 1));
          // 如果计算出的最大时间超过当前时间，则使用当前时间
          if (maxDate.isAfter(DateTime.now())) {
            maxDate = DateTime.now();
          }
          // 确保初始时间在有效范围内
          if (initialDateTime.isBefore(minDate)) {
            // 如果初始时间早于开始时间，设置为开始时间+1秒（允许同一分钟）
            initialDateTime = startDateTime.add(const Duration(seconds: 1));
            // 但如果开始时间的秒数已经是59，则设置为下一分钟
            if (startDateTime.second >= 59) {
              initialDateTime = startDateTime.add(const Duration(minutes: 1));
              initialDateTime = DateTime(
                initialDateTime.year,
                initialDateTime.month,
                initialDateTime.day,
                initialDateTime.hour,
                initialDateTime.minute,
                0,
              );
            }
          }
          if (initialDateTime.isAfter(maxDate)) {
            initialDateTime = maxDate;
          }
        } catch (e) {
          minDate = DateTime(2020, 1, 1);
          maxDate = DateTime.now();
        }
      } else {
        minDate = DateTime(2020, 1, 1);
        maxDate = DateTime.now();
      }
    }

    DateTime tempSelectedDateTime = initialDateTime;

    // 防止重复打开弹出框
    if (Get.isBottomSheetOpen == true) {
      return;
    }

    Get.bottomSheet(
      Container(
        height: 600.h,
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(24.r),
            topRight: Radius.circular(24.r),
          ),
        ),
        child: Column(
          children: [
            // 顶部标题栏
            Container(
              height: 80.h,
              padding: EdgeInsets.symmetric(horizontal: 32.w),
              decoration: BoxDecoration(
                color: Colors.white,
                border: Border(
                  bottom: BorderSide(
                    color: const Color(0xFFE5E7EB),
                    width: 1.w,
                  ),
                ),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  GestureDetector(
                    onTap: () {
                      // 取消时清空对应的时间
                      if (isStartTime) {
                        controller.clearStartTime();
                      } else {
                        controller.clearEndTime();
                      }
                      Get.back();
                    },
                    child: Text(
                      '取消',
                      style: TextStyle(
                        fontSize: 32.sp,
                        color: const Color(0xFF047FF7),
                      ),
                    ),
                  ),
                  Text(
                    isStartTime ? '选择开始时间' : '选择结束时间',
                    style: TextStyle(
                      fontSize: 32.sp,
                      fontWeight: FontWeight.w600,
                      color: const Color(0xFF333333),
                    ),
                  ),
                  if (isStartTime)
                    GestureDetector(
                      onTap: () {
                        // 验证开始时间
                        // 开始时间的秒数应该从00开始
                        final startDateTime = DateTime(
                          tempSelectedDateTime.year,
                          tempSelectedDateTime.month,
                          tempSelectedDateTime.day,
                          tempSelectedDateTime.hour,
                          tempSelectedDateTime.minute,
                          0, // 秒数从00开始
                        );

                        if (controller.endTime.value.isNotEmpty) {
                          try {
                            final endDateTime = DateTime.parse(
                              controller.endTime.value.replaceAll(' ', 'T'),
                            );

                            // 检查开始时间是否晚于结束时间
                            // 允许同一分钟，但开始时间的秒数（00）必须小于结束时间的秒数
                            final isSameMinute =
                                startDateTime.year == endDateTime.year &&
                                startDateTime.month == endDateTime.month &&
                                startDateTime.day == endDateTime.day &&
                                startDateTime.hour == endDateTime.hour &&
                                startDateTime.minute == endDateTime.minute;

                            if (isSameMinute) {
                              // 同一分钟时，开始时间的秒数（00）必须小于结束时间的秒数
                              if (0 >= endDateTime.second) {
                                Get.snackbar(
                                  '提示',
                                  '开始时间不能晚于结束时间',
                                  snackPosition: SnackPosition.TOP,
                                  backgroundColor: const Color(0xFFFF6B6B),
                                  colorText: Colors.white,
                                );
                                return;
                              }
                            } else {
                              // 不同分钟时，开始时间不能晚于结束时间
                              if (startDateTime.isAfter(endDateTime)) {
                                Get.snackbar(
                                  '提示',
                                  '开始时间不能晚于结束时间',
                                  snackPosition: SnackPosition.TOP,
                                  backgroundColor: const Color(0xFFFF6B6B),
                                  colorText: Colors.white,
                                );
                                return;
                              }
                            }

                            // 检查时间跨度是否超过1小时
                            final duration = endDateTime.difference(
                              startDateTime,
                            );
                            if (duration.inSeconds > 3600) {
                              Get.snackbar(
                                '提示',
                                '时间跨度不能超过1小时',
                                snackPosition: SnackPosition.TOP,
                                backgroundColor: const Color(0xFFFF6B6B),
                                colorText: Colors.white,
                              );
                              return;
                            }
                          } catch (e) {
                            // 解析失败，继续设置
                          }
                        }
                        controller.setStartTime(startDateTime);
                        Get.back();
                        // 自动打开结束时间选择
                        Future.delayed(Duration(milliseconds: 300), () {
                          _showTimePicker(false);
                        });
                      },
                      child: Text(
                        '确定',
                        style: TextStyle(
                          fontSize: 32.sp,
                          color: const Color(0xFF047FF7),
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    )
                  else
                    // 结束时间选择时没有确定按钮，只有取消
                    SizedBox(width: 60.w),
                ],
              ),
            ),

            // 年月日时分秒选择器 - 单独列显示，不显示星期
            Expanded(
              child: Container(
                color: Colors.white,
                child: CupertinoDatePicker(
                  mode: CupertinoDatePickerMode.dateAndTime,
                  initialDateTime: initialDateTime,
                  minimumDate: minDate,
                  maximumDate: maxDate,
                  onDateTimeChanged: (DateTime dateTime) {
                    tempSelectedDateTime = dateTime;
                    // 结束时间选择时，验证并自动设置时间
                    if (!isStartTime) {
                      // 验证结束时间
                      if (controller.startTime.value.isNotEmpty) {
                        try {
                          final startDateTime = DateTime.parse(
                            controller.startTime.value.replaceAll(' ', 'T'),
                          );
                          // 检查结束时间是否早于或等于开始时间
                          // 允许同一分钟，但结束时间的秒数必须大于开始时间的秒数
                          final isSameMinute =
                              dateTime.year == startDateTime.year &&
                              dateTime.month == startDateTime.month &&
                              dateTime.day == startDateTime.day &&
                              dateTime.hour == startDateTime.hour &&
                              dateTime.minute == startDateTime.minute;

                          if (isSameMinute) {
                            // 同一分钟时，结束时间的秒数必须大于开始时间的秒数
                            if (dateTime.second <= startDateTime.second) {
                              Get.snackbar(
                                '提示',
                                '结束时间必须晚于开始时间',
                                snackPosition: SnackPosition.TOP,
                                backgroundColor: const Color(0xFFFF6B6B),
                                colorText: Colors.white,
                              );
                              return;
                            }
                          } else {
                            // 不同分钟时，结束时间必须晚于开始时间
                            if (dateTime.isBefore(startDateTime) ||
                                dateTime.isAtSameMomentAs(startDateTime)) {
                              Get.snackbar(
                                '提示',
                                '结束时间必须晚于开始时间',
                                snackPosition: SnackPosition.TOP,
                                backgroundColor: const Color(0xFFFF6B6B),
                                colorText: Colors.white,
                              );
                              return;
                            }
                          }
                          // 检查时间跨度是否超过1小时
                          final duration = dateTime.difference(startDateTime);
                          if (duration.inSeconds > 3600) {
                            Get.snackbar(
                              '提示',
                              '时间跨度不能超过1小时',
                              snackPosition: SnackPosition.TOP,
                              backgroundColor: const Color(0xFFFF6B6B),
                              colorText: Colors.white,
                            );
                            return;
                          }
                        } catch (e) {
                          // 解析失败，继续设置
                        }
                      }
                      controller.setEndTime(dateTime);
                    }
                  },
                  dateOrder: DatePickerDateOrder.ymd,
                  use24hFormat: true,
                ),
              ),
            ),

            // 结束时间选择时显示开始下载按钮
            if (!isStartTime) ...[
              Container(
                padding: EdgeInsets.symmetric(horizontal: 32.w, vertical: 20.h),
                child: Obx(
                  () => SizedBox(
                    width: double.infinity,
                    child: ElevatedButton(
                      onPressed:
                          controller.startTime.value.isNotEmpty &&
                                  controller.endTime.value.isNotEmpty
                              ? () {
                                // 开始下载逻辑
                                _startDownload();
                              }
                              : null,
                      style: ElevatedButton.styleFrom(
                        backgroundColor:
                            controller.startTime.value.isNotEmpty &&
                                    controller.endTime.value.isNotEmpty
                                ? const Color(0xFF047FF7)
                                : const Color(0xFFE5E7EB),
                        foregroundColor:
                            controller.startTime.value.isNotEmpty &&
                                    controller.endTime.value.isNotEmpty
                                ? Colors.white
                                : const Color(0xFF999999),
                        padding: EdgeInsets.symmetric(vertical: 20.h),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12.r),
                        ),
                      ),
                      child: Text(
                        '开始下载',
                        style: TextStyle(
                          fontSize: 32.sp,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ],
        ),
      ),
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
    );
  }

  /// 开始下载
  void _startDownload() {
    if (controller.startTime.value.isEmpty ||
        controller.endTime.value.isEmpty) {
      Get.snackbar(
        '提示',
        '请先选择开始时间和结束时间',
        snackPosition: SnackPosition.TOP,
        backgroundColor: const Color(0xFFFF6B6B),
        colorText: Colors.white,
      );
      return;
    }

    // 验证时间范围
    try {
      final startDateTimeRaw = DateTime.parse(
        controller.startTime.value.replaceAll(' ', 'T'),
      );
      // 开始时间的秒数应该从00开始
      final startDateTime = DateTime(
        startDateTimeRaw.year,
        startDateTimeRaw.month,
        startDateTimeRaw.day,
        startDateTimeRaw.hour,
        startDateTimeRaw.minute,
        0, // 秒数从00开始
      );
      final endDateTime = DateTime.parse(
        controller.endTime.value.replaceAll(' ', 'T'),
      );

      // 验证结束时间不能早于或等于开始时间
      // 允许同一分钟，但结束时间的秒数必须大于开始时间的秒数（00）
      final isSameMinute =
          endDateTime.year == startDateTime.year &&
          endDateTime.month == startDateTime.month &&
          endDateTime.day == startDateTime.day &&
          endDateTime.hour == startDateTime.hour &&
          endDateTime.minute == startDateTime.minute;

      if (isSameMinute) {
        // 同一分钟时，结束时间的秒数必须大于开始时间的秒数（00）
        if (endDateTime.second <= 0) {
          Get.snackbar(
            '提示',
            '结束时间必须晚于开始时间',
            snackPosition: SnackPosition.TOP,
            backgroundColor: const Color(0xFFFF6B6B),
            colorText: Colors.white,
          );
          return;
        }
      } else {
        // 不同分钟时，结束时间必须晚于开始时间
        if (endDateTime.isBefore(startDateTime) ||
            endDateTime.isAtSameMomentAs(startDateTime)) {
          Get.snackbar(
            '提示',
            '结束时间必须晚于开始时间',
            snackPosition: SnackPosition.TOP,
            backgroundColor: const Color(0xFFFF6B6B),
            colorText: Colors.white,
          );
          return;
        }
      }

      // 验证时间跨度不能超过1小时
      final duration = endDateTime.difference(startDateTime);
      if (duration.inSeconds > 3600) {
        Get.snackbar(
          '提示',
          '时间跨度不能超过1小时',
          snackPosition: SnackPosition.TOP,
          backgroundColor: const Color(0xFFFF6B6B),
          colorText: Colors.white,
        );
        return;
      }
    } catch (e) {
      Get.snackbar(
        '提示',
        '时间格式错误，请重新选择',
        snackPosition: SnackPosition.TOP,
        backgroundColor: const Color(0xFFFF6B6B),
        colorText: Colors.white,
      );
      return;
    }

    // 关闭底部弹出框
    Get.back();

    // 调用控制器的时间范围下载方法
    controller.downloadTimeRange();
  }

  /// 构建默认背景
  Widget _buildDefaultBackground(String type) {
    return Container(
      width: double.infinity,
      height: double.infinity,
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors:
              type == 'alarm'
                  ? [Color(0xFFFF6B35), Color(0xFFFF4444)] // 告警录像用橙红色
                  : [Color(0xFF3C3C3C), Color(0xFF2C2C2C)], // 普通录像用灰色
        ),
      ),
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              type == 'alarm' ? Icons.warning : Icons.play_circle_outline,
              size: 32.w,
              color: Colors.white70,
            ),
            if (type == 'alarm')
              Padding(
                padding: EdgeInsets.only(top: 4.h),
                child: Text(
                  '告警',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 16.sp,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }

  /// 显示日期选择器
  void _showDatePicker() {
    // 解析当前选中的日期作为初始值
    DateTime initialDate;
    try {
      initialDate = DateTime.parse(controller.selectedDate.value);
    } catch (e) {
      print('解析日期失败，使用当前日期: $e');
      initialDate = DateTime.now();
    }

    DateTime tempSelectedDate = initialDate;

    Get.bottomSheet(
      Container(
        height: 500.h,
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(24.r),
            topRight: Radius.circular(24.r),
          ),
        ),
        child: Column(
          children: [
            // 顶部标题栏
            Container(
              height: 100.h,
              padding: EdgeInsets.symmetric(horizontal: 32.w),
              decoration: BoxDecoration(
                color: Colors.white,
                border: Border(
                  bottom: BorderSide(
                    color: const Color(0xFFE5E7EB),
                    width: 1.w,
                  ),
                ),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  GestureDetector(
                    onTap: () => Get.back(),
                    child: Text(
                      '取消',
                      style: TextStyle(
                        fontSize: 34.sp,
                        color: const Color(0xFF047FF7),
                      ),
                    ),
                  ),
                  Text(
                    '选择日期',
                    style: TextStyle(
                      fontSize: 34.sp,
                      fontWeight: FontWeight.w600,
                      color: const Color(0xFF333333),
                    ),
                  ),
                  GestureDetector(
                    onTap: () {
                      controller.setSelectedDate(tempSelectedDate);
                      Get.back();
                    },
                    child: Text(
                      '确定',
                      style: TextStyle(
                        fontSize: 34.sp,
                        color: const Color(0xFF047FF7),
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  ),
                ],
              ),
            ),

            // iOS风格日期选择器
            Expanded(
              child: Container(
                color: Colors.white,
                child: CupertinoDatePicker(
                  mode: CupertinoDatePickerMode.date,
                  initialDateTime: initialDate,
                  minimumDate: DateTime(2020, 1, 1),
                  maximumDate: DateTime.now(),
                  onDateTimeChanged: (DateTime date) {
                    tempSelectedDate = date;
                  },
                  dateOrder: DatePickerDateOrder.ymd,
                ),
              ),
            ),
          ],
        ),
      ),
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
    );
  }
}
